package com.quarters.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quarters.bean.*;
import com.quarters.bean.layuiBean.ResultPage;
import com.quarters.bean.layuiBean.VoPage;
import com.quarters.mapper.UserInfoMapper;
import com.quarters.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quarters.util.Respons.ResponseUtil;
import com.quarters.util.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2019-09-02
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    MenuService menuService;
    @Autowired
    RoleService roleService;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    RoleMenuService roleMenuService;
    @Autowired
    RoleQuartersService roleQuartersService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    UserService userService;

    /**
     * @param username
     * @param password
     * @param session
     * @return 后台登陆
     */
    @Override
    public boolean login(String username, String password, HttpSession session) {
        Map map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        List<UserInfo> users = baseMapper.login(map);
        //如果用户存在，放入session域
        if (users.size() > 0) {
            boolean flag = users.get(0).getPassword().equals(password);
            if (flag) {
                users.get(0).getRoles().setMenus(menuService.findMenuByRole(users.get(0).getRoles()));
                session.setAttribute("userInfo", users.get(0));
                System.err.println("Impl层:" + users.get(0).toString());
                return true;
            } else {
                System.out.println("密码错误---用户输入密码:" + password);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * @param voPage
     * @return 后台查询
     */
    @Override
    public ResultPage<UserInfo> selectMyPage(VoPage voPage, Long userId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        paramMap.put("userId", userId);
        List<UserInfo> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<UserInfo> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    /**
     * @param username
     * @param password
     * @param menuId
     * @param id
     * @return 添加角色
     */
    @Override
    public Map<String, Object> saveUserInfo(
            String username, String password, String menuId, String quartersId,
            String roleName, String openId, Long id,Integer flage) {

        String mm = "1,2,12,13,15,16,17,18";

        //查询数据库是否存在该用户名,已经存在提示已存在不让添加
        List<UserInfo> list = userInfoService.list();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUsername().equals(username)) {
                throw new CommonException("该用户已存在");
            }
        }
        //否则就添加用户和角色等等关联东西
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        userInfo.setParentId(id);
        userInfo.setOpenId(openId);
        userInfo.setCreateTime(System.currentTimeMillis());
        //添加user
        if (this.save(userInfo)) {
            //添加role
            Role role = new Role();
            role.setUserId(userInfo.getId());
            role.setRoleValue(UUID.randomUUID() + "");
            role.setRoleName(roleName);
            if (roleService.save(role)) {
                RoleUser roleUser = new RoleUser();
                roleUser.setUserId(userInfo.getId());
                roleUser.setRoleId(role.getId());
                //角色用户关联表
                if (roleUserService.save(roleUser)) {
                    if(flage==1){
                        String mmIds[] = mm.split(",");
                        for (int i = 0; i < mmIds.length; i++) {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setMenuId(Long.parseLong(mmIds[i]));
                            roleMenu.setRoleId(role.getId());//角色菜单关联表
                            if (!roleMenuService.save(roleMenu)) {
                                throw new CommonException("保存角色失败");
                            }
                        }
                    }else{
                        String mIds[] = menuId.split(",");
                        for (int i = 0; i < mIds.length; i++) {
                            RoleMenu roleMenu = new RoleMenu();
                            roleMenu.setMenuId(Long.parseLong(mIds[i]));
                            roleMenu.setRoleId(role.getId());//角色菜单关联表
                            if (!roleMenuService.save(roleMenu)) {
                                throw new CommonException("保存角色失败");
                            }
                        }
                    }

                    String quartersIds[] = quartersId.split(",");
                    for (int i = 0; i < quartersIds.length; i++) {
                        RoleQuarters roleQuarters = new RoleQuarters();
                        roleQuarters.setQuartersId(Long.parseLong(quartersIds[i]));
                        roleQuarters.setRoleId(role.getId());
                        roleQuarters.setFlage(flage);
                        if (!roleQuartersService.save(roleQuarters)) {
                            throw new CommonException("保存角色失败(小区)");
                        }
                    }
                }
            }
        }
        return ResponseUtil.getSuccessMap();
    }

    /**
     * @param id
     * @return 删除角色
     */
    @Override
    public Map deleteByIdUserInfo(Long id) {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfoService.removeById(id)) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id", id);
            RoleUser roleUser = roleUserService.getOne(queryWrapper);
            if (roleUserService.removeById(roleUser.getId())) {
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("id", roleUser.getRoleId());
                Role role = roleService.getOne(queryWrapper1);
                if (roleService.removeById(role.getId())) {
                    QueryWrapper queryWrapper2 = new QueryWrapper();
                    queryWrapper2.eq("role_id", role.getId());
                    List<RoleMenu> roleMenus = roleMenuService.list(queryWrapper2);
                    for (int i = 0; i < roleMenus.size(); i++) {
                        if (!roleMenuService.removeById(roleMenus.get(i).getId())) {
                            return ResponseUtil.RequestException("删除RoleMenu失败");
                        }
                    }

                    QueryWrapper queryWrapper3 = new QueryWrapper();
                    queryWrapper3.eq("role_id", role.getId());
                    List<RoleQuarters> quarters = roleQuartersService.list(queryWrapper3);
                    for (int i = 0; i < quarters.size(); i++) {
                        if (!roleQuartersService.removeById(quarters.get(i).getId())) {
                            return ResponseUtil.RequestException("删除小区失败");
                        }
                    }

                } else {
                    return ResponseUtil.RequestException("删除role失败");
                }
            } else {
                return ResponseUtil.RequestException("删除RoleUser失败");
            }
        } else {
            return ResponseUtil.RequestException("删除UserInfo失败");
        }
        return ResponseUtil.getSuccessMap();
    }

    /**
     * @param userId
     * @return 查询当前用户的下级管理范围
     */
    @Override
    public List<UserInfo> selectName(Long userId) {
        return baseMapper.selectName(userId);
    }


}
